<script setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { searchForumArticleService } from '@/api/forumArticle';

const router = useRouter()
const route = useRoute()

const articleCondition = ref({
  title: "",
  orderType: 0,
  pageNum: 1, // 页数
  pageSize: 10, // 每页条数
})

const forumArticleList = ref([])

// 文章搜索
const search = async () => {

  // 如果已经在加载了，就不执行文章搜索，防止等待加载期间多次搜索
  if (pageLoading.value || pageFinished.value) return

  // 开始搜索，显示加载框
  pageLoading.value = true
  pageError.value = null

  try {
    let res = await searchForumArticleService(articleCondition.value)
    console.log("文章搜索结果", res)
    forumArticleList.value.push(...res.data)

    // 页数+1
    articleCondition.value.pageNum++

    // 判断是否还有更多数据
    if (res.data.length < articleCondition.value.pageSize) { // 没有更多数据了
      pageFinished.value = true
    }

  } catch (err) {
    pageError.value = err.message || '请求失败'
    console.error('请求错误:', err)
  } finally {
    pageLoading.value = false
  }

  // loading.value = true
  // let res = await searchForumArticleService(articleCondition.value)
  // loading.value = false

  // console.log("文章搜索结果", res)
  // forumArticleList.value.push(...res.data)
}

// 搜索条件切换
const handleTabChange = (tab) => {
  articleCondition.value.orderType = tab.props.name
  articleCondition.value.pageNum = 1
  forumArticleList.value = []
  pageFinished.value = false
  pageLoading.value = false
  search()
}

// 点击搜索按钮进行搜索
const click_btn_search = () => {
  console.log("点击搜索按钮")

  console.log("文章title：", articleCondition.value.title)
  console.log("路由query参数：", route.query)
  // 如果路由未发生变化（例如 /user/123 -> /user/123），手动触发更新
  if (articleCondition.value.title == route.query.title) {
    console.log('路由未变化，手动更新状态');
    // 文章列表置空
    forumArticleList.value = []
    // 搜索条件中的板块信息置空
    articleCondition.value.orderType = 0
    articleCondition.value.pageNum = 1
    articleCondition.value.pageSize = 10
    // 重新搜索文章
    search()
    return
  }

  // 走到这里表明路由需要发生变化
  // router.push({
  router.replace({
    path: '/search',
    query: {
      title: articleCondition.value.title
    }
  })
}

// 滚动处理
const pageLoading = ref(false)
const pageFinished = ref(false)
const pageError = ref(null)
const handleScroll = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight

  // 距离底部50px时加载
  if (scrollTop + windowHeight >= scrollHeight - 50 && !pageLoading.value && !pageFinished.value) {
    console.log("要翻页喽")
    search()
  }
}

// 添加滚动监听
onMounted(() => {
  window.addEventListener('scroll', handleScroll)
  // fetchData() // 初始加载
})

// 移除滚动监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})


// 若页面滚动到底部则继续加载数据
// let flat = true; // 设置节流的开关阀门
// window.addEventListener('scroll', () => {
//   // 获取整个文档的高度
//   let docHeight = document.documentElement.scrollHeight;
//   // 获取视口（可见区域）的高度
//   let viewportHeight = window.innerHeight || document.documentElement.clientHeight;
//   // 获取当前滚动条垂直方向上的滚动距离
//   let scrollTop = window.pageYOffset || document.documentElement.scrollTop;

//   // 检查是否滚动到底部
//   if (scrollTop + viewportHeight >= docHeight) {
//     console.log("已经滚动到底部");
//     // 判断阀门是否开着
//     if (flat == false) {
//       return
//     }
//     // 进来后关闭阀门
//     flat = false;
//     // 页数+1
//     articleCondition.value.pageNum = articleCondition.value.pageNum + 1
//     // 获取新的文章数据
//     search()

//     setTimeout(() => {
//       console.log("开启计时器")
//       flat = true; // 每过1秒开启一次阀门（允许请求加载数据）
//     }, 1000); // 模拟1秒的加载时间
//   }
// });

// watch(
//   () => route.params,
//   (newValue, oldValue) => {
//     console.log(`用户 ID 从 ${newValue} 变化到 ${oldValue}`);
//   }
// )

watch(
  () => route.query,
  (newValue, oldValue) => {
    console.log("content页面的路由参数：", newValue)
    if (newValue == undefined || newValue == null) {
      console.log("当前无路由")
      return
    }

    // 文章列表置空
    forumArticleList.value = []
    // 设置搜索条件
    articleCondition.value.title = newValue.title
    // 搜索条件中的板块信息置空
    articleCondition.value.orderType = 0
    articleCondition.value.pageNum = 1
    articleCondition.value.pageSize = 10

    // 文章搜索
    search()
  },
  { immediate: true, deep: true }
)

onMounted(() => {
  // 进入文章搜索页面，隐藏掉Header中的搜索栏
  document.querySelector(".search").style.display = 'none'
})

onUnmounted(() => {
  // 离开文章搜索页面，显示Header中的搜索栏
  document.querySelector(".search").style.display = 'flex'
})
</script>

<template>
  <div class="search-list">
    <!-- 搜索框 -->
    <div class="search-panel">
      <div class="wrapper">
        <div class="search-panel-main">
          <input type="text" v-model="articleCondition.title" @keyup.enter="click_btn_search()">
          <button class="search-panel-btn">
            <span class="iconfont icon-sousuo" style="padding-right: 5px;font-size: 19px;"></span>
            <span @click="click_btn_search()">搜索</span>
          </button>
        </div>
      </div>
    </div>
    <div class="main-box">
      <!-- 搜索条件 -->
      <div class="list-header">
        <el-tabs v-model="articleCondition.orderType" class="demo-tabs" @tab-click="handleTabChange">
          <el-tab-pane label="综合" :name="0"></el-tab-pane>
          <el-tab-pane label="最新" :name="1"></el-tab-pane>
        </el-tabs>
      </div>
      <!-- 搜索结果 -->
      <div class="result-box">
        <div class="wrapper">
          <!--骨架过渡效果  -->
          <!-- <div class="skeleton" v-if="forumArticleList.length == 0">
            <el-skeleton :row="2" animated></el-skeleton>
          </div>
          <div v-if="forumArticleList.length == 0" class="empty-res">
            <el-empty description="暂无数据" />
          </div> -->
          <div class="box-l">
            <ul>
              <li v-for="(item) in forumArticleList" style="border-bottom: 1px solid #ededed;">
                <div class="item-h">
                  <span v-html="item.title" class="item-h-title"
                    @click="router.push(`/article/detail/${item.articleId}`)"></span>
                </div>
                <div class="item-bd">
                  <div class="item-bd-cont">
                    <div class="item-bd-cont-l">
                      <div class="item-l-sum" v-html="item.summary"></div>
                      <div class="item-l-b">
                        <div class="btm-l">
                          <div class="btm-item">
                            <span class="iconfont icon-eye"></span>
                            <span>{{ item.readCount }}</span>
                          </div>
                          <div class="btm-item">
                            <span class="iconfont icon-appreciate"></span>
                            <span>{{ item.likeCount }}</span>
                          </div>
                          <div class="btm-item">
                            <span class="iconfont icon-review"></span>
                            <span>{{ item.commentCount }}</span>
                          </div>
                        </div>
                        <div class="btm-r">
                          <router-link :to="`/userCenter/${123}`" class="btm-username">{{ item.nickname }}</router-link>
                          <span>{{ item.postTime.split(' ')[0] }}</span>
                        </div>
                      </div>
                    </div>
                    <div class="item-bd-cont-r" v-if="item.cover">
                      <img :src="item.cover" alt="" class="item-bd-cont-r-img">
                    </div>
                  </div>
                </div>
              </li>
            </ul>
            <!-- 翻页时出现 -->
            <!-- 加载状态 -->
            <div v-if="pageLoading" class="pageLoading">加载中...</div>
            <!-- 没有更多数据 -->
            <div v-if="pageFinished" class="no-more">没有更多数据了</div>
            <!-- 错误提示 -->
            <div v-if="pageError" class="error">{{ pageError }}</div>
          </div>
          <!-- 右侧 -->
          <div class="box-r">
            <!-- 个人名片 -->
            <div class="author-qrcode">
              <div class="author-qrcode-title">
                <span class="iconfont icon-weixin"></span>
                <span class="text">联系作者</span>
              </div>
              <img class="author-qrcode-img" src="../../assets/caoliao_vm_mingpian.png" alt="">
            </div>
            <!-- 其他 -->
            <div class="other-bbb"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-list {
  height: 60px;
  width: 100%;
}

/* 搜索框 */
.search-list .search-panel {
  box-shadow: 0 4px 14px 0 rgba(0, 0, 0, .05);
  padding: 5px;
  height: 100%;
  display: flex;
  align-items: center;
}

.search-list .search-panel .wrapper {
  height: 100%;
  width: 1300px;
  margin: 0 auto;
  background: #fff;
}

.search-list .search-panel .wrapper .search-panel-main {
  height: 100%;
  display: flex;
  align-items: center;
}

.search-list .search-panel .wrapper .search-panel-main input {
  padding: 8px 30px 8px 0;
  border: 0px;
  outline: none;
  color: #000;
  font-size: 14px;
  text-indent: 16px;
  border: 1px solid rgba(0, 0, 0, .06);
  border-radius: 2px 0 0 2px;
  background: #f5f6f7;
  width: 1000px;
  height: 40px;
}

.search-list .search-panel .wrapper .search-panel-main input::placeholder {
  color: #000;
}

.search-list .search-panel .wrapper .search-panel-main input:focus {
  border-color: green;
  background: #fff;
  border-radius: 4px 0 0 0;
}

.search-list .search-panel .wrapper .search-panel-main .search-panel-btn {
  height: 40px;
  width: 120px;
  border: 0;
  outline: none;
  border-radius: 0 2px 2px 0;
  cursor: pointer;
  font-size: 20px;
  font-weight: 600;
  color: #fff;
  background: linear-gradient(80deg, green 0, #67C23A 100%);
  border-radius: 0 5px 5px 0;
}

.search-list .main-box {
  padding: 10px 0;
  background-color: #f2f2f2;
  min-height: calc(100vh - 120px);
}

/* 搜索条件 */
.search-list .main-box .list-header {
  border-bottom: 1px solid #e4e6eb;
  padding: 5px 20px 0px;
  font-size: 15px;
  width: 1300px;
  margin: 0 auto;
  background-color: #fff;
  margin-bottom: 10px;
}

/* 搜索结果 */
.search-list .main-box .result-box {}

.search-list .main-box .result-box .wrapper {
  width: 1300px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
}

.search-list .main-box .result-box .wrapper .skeleton {
  width: 100%;
  background-color: #fff;
}

.search-list .main-box .result-box .wrapper .empty-res {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
}

.search-list .main-box .result-box .wrapper .box-l {
  flex: 1;
  min-width: 990px;
  max-width: 990px;
}

.search-list .main-box .result-box .wrapper .box-l ul li {
  padding: 16px 24px;
  background-color: #fff;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-h {
  font-size: 18px;
  color: #222226;
  margin-bottom: 5px;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-h .item-h-title {
  cursor: pointer;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-h .item-h-title:hover {
  color: green;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l {
  flex: 1;
  height: 74px;
  font-size: 14px;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l .item-l-sum {
  height: 48px;
  max-height: 48px;
  line-height: 24px;
  color: #555666;

  /* 设置最多显示两行，多出的显示省略号 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l .item-l-b {
  padding-top: 5px;
  height: 26px;
  color: #555666;
  display: flex;
  justify-content: space-between;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l .item-l-b .btm-l {
  display: flex;
  align-items: center;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l .item-l-b .btm-l .btm-item {
  margin-right: 30px;
  display: flex;
  align-items: center;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l .item-l-b .btm-l .btm-item .iconfont {
  margin-right: 5px;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l .item-l-b .btm-r {
  display: flex;
  align-items: center;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l .item-l-b .btm-r .btm-username {
  margin-right: 20px;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-l .item-l-b .btm-r .btm-username:hover {
  color: green;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-r {
  width: 128px;
  height: 74px;
  margin-left: 24px;
}

.search-list .main-box .result-box .wrapper .box-l ul li .item-bd .item-bd-cont .item-bd-cont-r .item-bd-cont-r-img {
  width: 100%;
  height: 100%;
  /* 使用cover不会出现留空白 */
  object-fit: cover;
  /* background-color: blue; */
  border-radius: 4px;
}

/* 翻页相关 */
.pageLoading,
.no-more,
.error {
  padding: 15px;
  text-align: center;
  color: #999;
}

.error {
  color: #f56c6c;
}

/* 右侧 */
.search-list .main-box .result-box .wrapper .box-r {
  display: block !important;
  width: 300px;
  min-width: 300px;
  max-width: 300px;
  /* background-color: #fff; */
  margin-left: 10px;
  display: flex;
  justify-content: center;
  color: #555666;
}

/* 个人名片 */
.search-list .main-box .result-box .wrapper .box-r .author-qrcode {
  background-color: #fff;
  width: 100%;
  margin-bottom: 20px;
}

.search-list .main-box .result-box .wrapper .box-r .author-qrcode .author-qrcode-img {
  width: 100%;
  padding: 20px;
}

.search-list .main-box .result-box .wrapper .box-r .author-qrcode .author-qrcode-title {
  display: flex;
  align-items: center;
  justify-content: start;
  padding: 20px 15px;
  border-bottom: 1px solid #ebeef5;
}

.search-list .main-box .result-box .wrapper .box-r .author-qrcode .author-qrcode-title .iconfont {
  font-size: 20px;
  color: green;
  margin-right: 15px;
}

.search-list .main-box .result-box .wrapper .box-r .author-qrcode .author-qrcode-title .text {
  font-size: 18px;
  font-weight: 700;
}

/* 其他 */
.search-list .main-box .result-box .wrapper .box-r .other-bbb {
  width: 100%;
  height: 500px;
}
</style>